package com.uwantsoft.interfaces.web.handler;

import com.uwantsoft.business.facade.dto.Result;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Chuanbao
 */
@ControllerAdvice(basePackages = {"com.uwantsoft.interfaces.web.controller.restful"})
public class ErrorHandler {
    Logger log = Logger.getLogger(ErrorHandler.class);

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public @ResponseBody ErrorResponse errorResponse(MethodArgumentNotValidException bindException) {
        log.info("Json request bind error:"+bindException.getMessage());
        List<FieldError> fieldErrors = bindException.getBindingResult().getFieldErrors();
        Map<String,String> errors = new HashMap<String, String>();
        for (FieldError fieldError : fieldErrors) {
            errors.put(fieldError.getField(),fieldError.getDefaultMessage());
        }
        return new ErrorResponse(errors);
    }
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public void errorResponse(Exception e) {
        log.info("Restful api request exception:"+e);
    }
}
